package com.ys.nms.module.business.libreApi.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class LibreNmsConfigFactory {

    private final Environment environment;

    public LibreNmsConfigFactory(Environment environment) {
        this.environment = environment;
    }

    /**
     * 根据当前激活的 profile 获取 LibreNMS 配置
     */
    public LibreNmsConfig getConfig() {
        String[] activeProfiles = environment.getActiveProfiles();

        if (activeProfiles.length == 0) {
            log.warn("No active profile found, using default config (fallback)");
            return createDefaultConfig();
        }

        String profile = activeProfiles[0];
        log.info("Loading LibreNMS config for profile: '{}'", profile);

        String baseUrl = getProperty(profile, "base-url");
        String token = getProperty(profile, "token");
        String timeoutStr = getProperty(profile, "timeout");
        String enabledStr = getProperty(profile, "enabled");

        LibreNmsConfig config = new LibreNmsConfig();

        if (baseUrl != null) config.setBaseUrl(baseUrl);
        if (token != null) config.setToken(token);
        if (timeoutStr != null) {
            try {
                config.setTimeout(Integer.valueOf(timeoutStr));
            } catch (NumberFormatException e) {
                log.warn("Invalid timeout value for profile '{}': {}", profile, timeoutStr);
            }
        }
        if (enabledStr != null) {
            config.setEnabled(Boolean.parseBoolean(enabledStr));
        }

        // 校验必要字段
        if (config.getBaseUrl() == null || config.getToken() == null) {
            log.error("Missing required config for profile '{}': baseUrl={}, token={}",
                    profile, config.getBaseUrl(), config.getToken() == null ? "MISSING" : "SET");
            throw new IllegalStateException("LibreNMS configuration is incomplete for profile: " + profile);
        }

        log.info("Loaded LibreNMS config: baseUrl={}, timeout={}ms, enabled={}",
                config.getBaseUrl(), config.getTimeout(), config.getEnabled());

        return config;
    }

    private String getProperty(String profile, String key) {
        return environment.getProperty("librenms." + profile + "." + key);
    }

    private LibreNmsConfig createDefaultConfig() {
        LibreNmsConfig config = new LibreNmsConfig();
        config.setBaseUrl("http://localhost:8000");
        config.setToken("fallback-token");
        config.setTimeout(5000);
        config.setEnabled(false);
        return config;
    }

    /**
     * 获取当前激活的 profile
     */
    public String getActiveProfile() {
        String[] profiles = environment.getActiveProfiles();
        return profiles.length > 0 ? profiles[0] : "default";
    }
}